﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

namespace WXBot
{
    public class SendMsgToDDClass
    {
        private static string DictionaryToJson(Dictionary<string, object> dic)
        {
            //实例化JavaScriptSerializer类的新实例  
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                //将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象  
                return jss.Serialize(dic);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public static void SendMsg2DD(WXObject.WXMsg rs)
        {
            if(rs.From != null && rs.From.Equals("XXX"))
            {
                Dictionary<string, object> dicData = new Dictionary<string, object>();
                dicData.Add("msgtype", "text");
                Dictionary<string, object> dictext = new Dictionary<string, object>();
                dictext.Add("content", rs.From2+"在WX说:"+ rs.Msg);
                dicData.Add("text",dictext);

                string postData = DictionaryToJson(dicData); // 要发放的数据 
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);

                HttpWebRequest objWebRequest = (HttpWebRequest)WebRequest.Create("https://oapi.dingtalk.com/robot/send?access_token=XXX");
                objWebRequest.Method = "POST";
                objWebRequest.ContentType = "application/json";
                objWebRequest.ContentLength = byteArray.Length;
                Stream newStream = objWebRequest.GetRequestStream();
                // Send the data. 
                newStream.Write(byteArray, 0, byteArray.Length); //写入参数 
                newStream.Close();

                HttpWebResponse response = (HttpWebResponse)objWebRequest.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string textResponse = sr.ReadToEnd(); // 返回的数据
            }
        }
    }
}
